package com.hongyi.modelcontest.modular.wechat.utils;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ExcelUtils {

    /**
     * 下载excel
     */
    public static void writeList(String fileName, List<String[]> list, String[] titles, HttpServletResponse response) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        int rowNum = 0;
        if (titles != null && titles.length > 0) {
            //写入标题
            HSSFRow row = sheet.createRow(rowNum);
            for (int i = 0; i < titles.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(titles[i]);
            }
            rowNum++;
        }
        for (int i = 0; i < list.size(); i++) {
            HSSFRow row = sheet.createRow(rowNum + i);
            String[] strings = list.get(i);
            if (strings.length > 0) {
                for (int k = 0; k < strings.length; k++) {
                    HSSFCell cell = row.createCell(k);
                    cell.setCellValue(strings[k]);
                }
            }
        }
        try {
            response.setContentType("application/octet-stream");//
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));// 设置文件名
            wb.write(response.getOutputStream());
            wb.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
